package com.cykj.interceptor;

import com.cykj.bean.Tbluser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截整个项目的所有请求(到控制器)
public class MyInterceptor implements HandlerInterceptor {

    //该方法将在处理请求之前进行调用
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        System.out.println("1");
        //在session中进行登录验证
        Tbluser tbluser=(Tbluser) httpServletRequest.getSession().getAttribute("tbluser");
        if (tbluser!=null){
            return true;
        }
        //获取请求路径
        String contextPath=httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(contextPath+"/login");
        return false;
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    //在当前处理请求之后调用，也就是在Controller方法调用之后执行的

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("2");
    }

    //必须在preHandle方法返回值为true的时候才会执行
    //垃圾回收
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
        System.out.println("3");
    }
}
